package com.m3839.sdk.common.thread;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

/**
 * @author ChenBaoyang
 * @description: ThreadHelper
 * @date 2021/11/18 16:26
 */
public class ThreadHelper {

    public static final int ON_WORK = 0x001;
    public static final int ON_FINISH = 0x002;

    private PersistentThread thread;

    private ThreadHelper() {}

    private static class SingleTon{
        private static ThreadHelper INSTANCE = new ThreadHelper();
    }

    public static ThreadHelper get() {
        return SingleTon.INSTANCE;
    }


    class PersistentThread extends Thread{

        /**
         * 需要执行的工作
         */
        private WorkTask task;

        /**
         * 表示{@link WorkTask#doWork()} 是否在主线程执行
         */
        private boolean workInMainThread;

        /**
         * 表示{@link WorkTask#onFinish()} ()} 是否在主线程执行
         */
        private boolean finishInMainThread;

        /**
         * 当前线程的Looper
         */
        private Looper looper;

        /**
         * 持有的handler, 用来切换线程
         */
        private Handler handler;



        public PersistentThread(WorkTask task, boolean workInMainThread, boolean finishInMainThread) {
            this.task = task;
            this.workInMainThread = workInMainThread;
            this.finishInMainThread = finishInMainThread;
        }


        @Override
        public void run() {
            //创建与当前线程相关的Looper
            Looper.prepare();


            if (workInMainThread) {
                looper = Looper.getMainLooper();
            }else{
                looper = Looper.myLooper();
            }
            //获取当前线程的Looper对象
            Log.d("HandlerThreadActivity", "Thread3------" + currentThread());
            handler = new InternalHandler(looper);
            //执行work接口的操作
            sendMessage(task);
            //调用此方法，消息才会循环处理
            Looper.loop();
        }

        public void quit() {
            if(looper != null) {
                looper.quit();
            }

        }

        /**
         * 发送消息
         *
         * @param work
         */
        public void sendMessage(WorkTask work) {
            Message message = handler.obtainMessage(ON_WORK, work);
            message.sendToTarget();
        }

        private void onWork() {
            task.doWork();
            boolean isOnMain = handler.getLooper() == Looper.getMainLooper();
            if(finishInMainThread) {
                if(!isOnMain) {
                    handler = new InternalHandler(Looper.getMainLooper());
                }
                Message message = handler.obtainMessage(ON_FINISH, task);
                message.sendToTarget();
            }else{
                task.onFinish();
            }

        }

        class InternalHandler extends Handler{

            public InternalHandler(Looper looper) {
                super(looper);
            }

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                WorkTask work = (WorkTask) msg.obj;
                if (ON_WORK == msg.what) {
                    onWork();
                }else if(ON_FINISH == msg.what) {
                    work.onFinish();
                }
            }
        }
    }


    public interface WorkTask{
        void doWork();
        void onFinish();
    }

    /**
     * 处理要任务内容
     *
     * @param workTask
     * @param isMainThread
     * @param endMainThread
     */
    public void handWork(WorkTask workTask, boolean isMainThread, boolean endMainThread) {
        thread = new PersistentThread(workTask, isMainThread, endMainThread);
        thread.start();
    }

    public void quitWork() {
        thread.quit();
    }

}
